<?php

namespace app\admin\service;

use think\facade\Filesystem;
use think\facade\Env;
use app\admin\lib\exception\BaseException;

class AvatarService
{
    /**
     * 处理头像上传
     * @param \think\File $file 上传的文件
     * @param int $userId 用户ID
     * @return string 头像URL
     * @throws BaseException
     */
    public function uploadAvatar($file, int $userId)
    {
        if (!$file) {
            return '';
        }

        // 文件类型验证
        $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $extension = strtolower($file->getOriginalExtension());
        
        if (!in_array($extension, $allowedTypes)) {
            throw new BaseException([
                'code' => 400,
                'message' => '只支持 jpg、jpeg、png、gif、webp 格式的图片',
                'errorCode' => 80001
            ]);
        }
        
        // 文件大小验证 (5MB)
        if ($file->getSize() > 5 * 1024 * 1024) {
            throw new BaseException([
                'code' => 400,
                'message' => '图片大小不能超过 5MB',
                'errorCode' => 80002
            ]);
        }
        
        // 生成唯一文件名
        $fileName = 'avatar_' . $userId . '_' . time() . '_' . uniqid() . '.' . $extension;
        
        // 创建上传目录
        $uploadDir = 'uploads/avatar/' . date('Y/m/d');
        $fullPath = Env::get('root_path') . 'public/' . $uploadDir;
        
        if (!is_dir($fullPath)) {
            mkdir($fullPath, 0755, true);
        }
        
        // 保存文件
        $savename = Filesystem::disk('public')->putFileAs($uploadDir, $file, $fileName);
        
        if (!$savename) {
            throw new BaseException([
                'code' => 500,
                'message' => '文件保存失败',
                'errorCode' => 80003
            ]);
        }
        
        // 返回访问URL
        return '/' . $savename;
    }

    /**
     * 删除头像文件
     * @param string $avatarUrl 头像URL
     * @return bool
     */
    public function deleteAvatar(string $avatarUrl)
    {
        if (empty($avatarUrl)) {
            return true;
        }

        $filePath = ltrim($avatarUrl, '/');
        $fullPath = Env::get('root_path') . 'public/' . $filePath;
        
        if (file_exists($fullPath)) {
            return unlink($fullPath);
        }
        
        return true;
    }

    /**
     * 获取默认头像URL
     * @return string
     */
    public function getDefaultAvatar()
    {
        return '/static/images/default-avatar.png';
    }

    /**
     * 验证头像URL是否有效
     * @param string $avatarUrl
     * @return bool
     */
    public function isValidAvatar(string $avatarUrl)
    {
        if (empty($avatarUrl)) {
            return false;
        }

        $filePath = ltrim($avatarUrl, '/');
        $fullPath = Env::get('root_path') . 'public/' . $filePath;
        
        return file_exists($fullPath);
    }
}
